﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;

namespace Api.Core.Filter
{
    public class GlobalExceptionsFilter : IExceptionFilter
    {
        private ILogger<GlobalExceptionsFilter> _logger;
        private readonly IWebHostEnvironment _env;

        public GlobalExceptionsFilter(ILogger<GlobalExceptionsFilter> logger,
             IWebHostEnvironment env)
        {
            _logger = logger;
            _env = env;
        }
        public void OnException(ExceptionContext context)
        {
            //if (context.ExceptionHandled == false)
            //{
            //    context.Result = new ContentResult
            //    {
            //        Content = new ResParameter { code = ResponseCode.exception, info = context.Exception.Message, data = "" }.ToJson(),//这里是把异常抛出。也可以不抛出。
            //        StatusCode = StatusCodes.Status200OK,
            //        ContentType = "text/html;charset=utf-8"
            //    };
            //}
            //context.ExceptionHandled = true;
            //var logIBLL = IocManager.Instance.GetService<LogIBLL>();
            //LogEntity logEntity = new LogEntity();
            //logEntity.F_CategoryId = 4;
            //logEntity.F_OperateTypeId = ((int)OperationType.Exception).ToString();
            //logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Exception);
            //logEntity.F_OperateAccount = ContextHelper.GetItem("account") as string;
            //logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
            //logEntity.F_Module = context.HttpContext.Request.Path;
            //logEntity.F_IPAddress = context.HttpContext.Connection.RemoteIpAddress.ToString();
            //logEntity.F_ExecuteResult = -1;
            //logEntity.F_ExecuteResultJson = logIBLL.ExceptionFormat(context.Exception);
            //logIBLL.Write(logEntity).GetAwaiter().GetResult();
            //return;
            string message;
            if (_env.IsDevelopment())
            {
                message = context.Exception.StackTrace;
            }
            else
            {
                message = context.Exception.Message;
            }

            context.Result = new InternalServerErrorObjectResult(message);

            _logger.LogError(message + WriteLog(message, context.Exception));
        }

        public string WriteLog(string throwMsg, Exception ex)
        {
            return string.Format("\r\n【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n【堆栈调用】：{3}", new object[] { throwMsg,
                ex.GetType().Name, ex.Message, ex.StackTrace });
        }
    }

    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object value) : base(value)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
}
